package com.taiyuan.tongcheng.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.utils.DensityUtils;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.StringUtils;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;

import com.taiyuan.tongcheng.adapter.OrderCancelAdapter;
import com.taiyuan.tongcheng.application.TCBroadcastAction;
import com.taiyuan.tongcheng.config.TcConfig;
import com.taiyuan.tongcheng.http.HttpParamUtil;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.tytc56.user.R;

public class OrderCancelActivity extends BaseActivity implements OnItemClickListener{

    //==initwidget
	@BindView(id=R.id.lv_order_cancel)
	private ListView  reasonLv;
	@BindView(id=R.id.etv_cancel_msg)
	private EditText  inputEv;
	@BindView(id = R.id.tv_driver_input)
	private TextView msgCount;
	@BindView(id=R.id.btn_reason_submit,click=true)
	private Button cancelBtn;
	private OrderCancelAdapter reasonAdapter;
	private int length = 0;
	private String orderId="";
	//==取消原因写入
	private int comFlag=0;
	public static  String TAG_CANCEL_KIND="TAG_CANCEL_KIND";
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_order_cancel);
	}
	
	@Override
	public void initData() {
		super.initData();
		inputEv.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				msgCount.setText((60 - count) + "/60");
				length = 60 - inputEv.getText().length();
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}
			@Override
			public void afterTextChanged(Editable s) {
				msgCount.setText(length + "/60");
			}
		});
	}
	
	@Override
	public void initWidget() {
		super.initWidget();
		initView();
		comFlag=getIntent().getIntExtra(TAG_CANCEL_KIND, 0);
		if(comFlag==OrderCancelAdapter.CANCEL_ADAPTER_CARGO){
			reasonAdapter=new OrderCancelAdapter(getApplicationContext(),OrderCancelAdapter.CANCEL_ADAPTER_CARGO);
			refreashUI(OrderCancelAdapter.CARGO_ORDER_CANCEL_NAME);
		}else if(comFlag==OrderCancelAdapter.CANCEL_ADAPTER_MOVING){
			reasonAdapter=new OrderCancelAdapter(getApplicationContext(),OrderCancelAdapter.CANCEL_ADAPTER_MOVING);
			refreashUI(OrderCancelAdapter.MOVING_ORDER_CANCEL_NAME);
		}
		reasonLv.setAdapter(reasonAdapter);
		reasonLv.setOnItemClickListener(this);
		topTv.setText(R.string.lable_cancel_order_title);
		rightTv.setVisibility(View.GONE);
		orderId=getIntent().getStringExtra(TcConfig.IntentTag.Order_Id);
	}
	
	private void refreashUI(String[] list) {
		LinearLayout.LayoutParams haltLisfLp =(LayoutParams)reasonLv.getLayoutParams();
		haltLisfLp.height=list.length*(DensityUtils.dip2px(this, 65)+DensityUtils.dip2px(this, 5));
		reasonLv.setLayoutParams(haltLisfLp);
	}

	@Override
	public void widgetClick(View v) {
		switch (v.getId()) {
		case R.id.btn_reason_submit:
			if(checkInput()){
				TcLoaddingDialog.show();
				if(comFlag==OrderCancelAdapter.CANCEL_ADAPTER_CARGO){
					cancelCargoOrder(orderId,reasonAdapter.getSelectPostion().getReasonId());
				}else if(comFlag==OrderCancelAdapter.CANCEL_ADAPTER_MOVING){
					cancelMovingOrder(orderId, reasonAdapter.getSelectPostion().getReasonId());
				}
				
			}else{
			}
			break;

		default:
			break;
		}
		super.widgetClick(v);
	}
	
	/**
	 * 
	* @Description: 检测输入内容是否有误？
	* @return
	* @return boolean
	* @throws
	* @autour Administrator
	* @date 2015-9-3 下午11:09:14 
	* @update (date)
	 */
	private boolean checkInput() {
		if(StringUtils.isEmpty(orderId)){
			showCustomToast(getString(R.string.lable_cancel_order_loseefficacy));
			return false;
		}
		if(reasonAdapter.getSelectPostion()==null){
			showCustomToast(getString(R.string.lable_cancel_order_title));
			return false;
		}
		return true;
	}

	/**
	 * 
	* @Description: 取消订单
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-9-1 下午4:03:13
	* @update (date)
	 */
	private void cancelCargoOrder(String orderId,int reasonId) {
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjHttp = new KJHttp(config);
        HttpParams params =new HttpParams();
        params=HttpParamUtil.getCancelOrderParams(OrderCancelActivity.this, reasonId, inputEv.getText().toString(), orderId);
        KJLoger.debug(params.getUrlParams().toString());
        kjHttp.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.FREIGHT_ORDER_CANCLE, params, new HttpCallBack() {
			@Override
			public void onFailure(int errorNo, String strMsg) {
				super.onFailure(errorNo, strMsg);
			}
			@Override
			public void onSuccess(String t) {
				try {
					String date=URLDecoder.decode(t, "UTF-8");
					KJLoger.debug(date);
					WebData webdata = TcJsParser.getWedataData(date); 
					if(webdata.getStatus()==1){
					    showCustomToast("取消订单成功");
					    sendBroadcast(new Intent(TCBroadcastAction.SUCCESS_CANCEL_CARGO));
					    OrderCancelActivity.this.finish();
					}else{
						showErroCustomToast("取消订单失败");
					}
					 if(TcLoaddingDialog.isShowing()){
						  TcLoaddingDialog.cancel();
					  }
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				super.onSuccess(t);
			}
        });
	}
	
	/**
	 * 
	* @Description: 取消订单
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-9-1 下午4:03:13
	* @update (date)
	 */
	private void cancelMovingOrder(String orderId,int reasonId) {
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjHttp = new KJHttp(config);
        HttpParams params =new HttpParams();
        params=HttpParamUtil.getMovingOrderCancel(orderId, getApplicationContext(), reasonId, inputEv.getText().toString());
        KJLoger.debug(params.getUrlParams().toString());
        kjHttp.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.MOVING_ORDER_CANCLE, params, new HttpCallBack() {
			@Override
			public void onFailure(int errorNo, String strMsg) {
				super.onFailure(errorNo, strMsg);
			}
			@Override
			public void onSuccess(String t) {
				try {
					String date=URLDecoder.decode(t, "UTF-8");
					KJLoger.debug(date);
					WebData webdata = TcJsParser.getWedataData(date); 
					if(webdata.getStatus()==1){
					    showCustomToast("取消订单成功");
					    sendBroadcast(new Intent(TCBroadcastAction.SUCCESS_CANCEL_CARGO));
					    OrderCancelActivity.this.finish();
					}else{
						showErroCustomToast(webdata.getMsg());
					}
					 if(TcLoaddingDialog.isShowing()){
						  TcLoaddingDialog.cancel();
					  }
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				super.onSuccess(t);
			}
        });
	}
	
	

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		reasonAdapter.setSlectPositon(arg2);
		reasonAdapter.notifyDataSetChanged();
	}
}
